 // 全局状态管理
const state = {
  fields: [
    {"customs": {}}
  ],
  formTitle: '领导信件自定义表单'
};

  // DOM 元素
const elements = {
      // 配置区域
      fieldsConfigInput: document.getElementById('fields-config'),
      loadSampleBtn: document.getElementById('load-sample-btn'),

      // 表单渲染区域
      renderedFormContainer: document.getElementById('rendered-form-container'),
      renderedForm: document.getElementById('rendered-form'),
      formPlaceholder: document.getElementById('form-placeholder'),
      formActions: document.getElementById('form-actions'),
      
      mobileMenu: document.getElementById('mobile-menu'),
      navbar: document.getElementById('navbar')
  };

  // 字段类型配置
  const fieldTypeConfig = {
      text: {
          label: '单行文本',
          icon: 'fa-font'
      },
      textarea: {
          label: '多行文本',
          icon: 'fa-align-left'
      },
      number: {
          label: '数字',
          icon: 'fa-hashtag'
      },
      date: {
          label: '日期',
          icon: 'fa-calendar'
      },
      select: {
          label: '下拉选择',
          icon: 'fa-list-ul'
      },
      multipleSelect: {
          label: '下拉多选',
          icon: 'fa-list-ul'
      },
      radio: {
          label: '单选框',
          icon: 'fa-dot-circle-o'
      },
      checkbox: {
          label: '复选框',
          icon: 'fa-check-square-o'
      },
      switch: {
          label: '开关',
          icon: 'fa-toggle-on'
      }
  };

  // 初始化事件监听
  function initEventListeners() {
      // 表单提交事件
      //elements.renderedForm.addEventListener('submit', handleFormSubmit);
  }

  // 解析字段配置
  function parseFieldsConfig(configJson) {
      try {
          // 去除JSON中的注释和多余空格
          const cleanedJson = configJson
              .replace(/\/\/.*$/gm, '') // 去除单行注释
              .replace(/\/\*[\s\S]*?\*\//g, '') // 去除多行注释
              .trim();
          
          const fields = JSON.parse(cleanedJson);
          
          // 验证字段配置
          if (!Array.isArray(fields)) {
              throw new Error('字段配置必须是一个数组');
          }
          
          fields.forEach((field, index) => {
              if (!field.key || !field.type) {
                  throw new Error(`第 ${index + 1} 个字段缺少必要属性（key 或 type）`);
              }
              
              if (!fieldTypeConfig[field.type]) {
                  throw new Error(`第 ${index + 1} 个字段包含不支持的类型: ${field.type}`);
              }
              
              // 验证选择类字段的选项配置
              if (['select', 'radio', 'checkbox','multipleSelect'].includes(field.type) && 
                  (!field.options || !Array.isArray(field.options) || field.options.length === 0)) {
                  throw new Error(`第 ${index + 1} 个字段（${field.name}）是选择类型，但未配置选项或选项为空`);
              }
          });
          
          return fields;
      } catch (error) {
          showErrorModal('解析配置失败', error.message, configJson);
          throw error;
      }
  }

  // 渲染表单
  function renderForm(letterConfig) {
      try {
          // 获取并更新表单标题
          state.formTitle =  '领导信箱自定义表单';
          
          // 解析字段配置
          const configJson = elements.fieldsConfigInput.value;

          state.fields = parseFieldsConfig(configJson);
          
          // 清空表单内容
          elements.renderedForm.innerHTML = '';
          
          // 隐藏占位符，显示表单操作按钮
          elements.formPlaceholder.classList.add('hidden');
          elements.formActions.classList.remove('hidden');
          
          // 动态生成表单字段
          state.fields.forEach(field => {
              const fieldElement = createFormField(field,letterConfig);
              elements.renderedForm.appendChild(fieldElement);
          });
          
          // 添加表单操作按钮
          elements.renderedForm.appendChild(elements.formActions);
          
          // 更新预览
          updateFormPreview();
          
      } catch (error) {
          console.error('表单渲染失败:', error);
      }
  }

  // 创建表单字段元素
  function createFormField(field,letterConfig) {
      const fieldWrapper = document.createElement('div');
      fieldWrapper.className = `form-group row form-field ${field.type}-field`;
      fieldWrapper.setAttribute('data-field-key', field.key);
      
      const labelClass = field.required ? 'col-sm-2 col-form-label after:content-["*"] after:text-danger' : 'col-sm-2 col-form-label';
      const requiredMark = field.required ? '<span class="text-danger ml-1">*</span>' : '';
      
      let fieldHtml = `
          <label class="${labelClass}" for="field-${field.key}">${field.name}${requiredMark}</label>
      `;
      // 根据字段类型生成不同的表单控件
      switch (field.type) {
          case 'text':
              if(letterConfig.openSmsValid&&field.code=="creatorPhone"){
                fieldHtml += `
                <div class="row col-sm-10">
                <div class="col-6">
                <input 
                    type="text" 
                    id="field-${field.key}" 
                    name="${field.key}" 
                    ${field.defValue ? `value="${field.defValue}"` : ''}
                    ${field.required ? 'required' : ''}
                    class="form-control"  
                    data-rule-pattern="^1\d{10}$" data-msg-pattern="请填写有效的手机号码" 
                    placeholder="请输入${field.name}"
                ></div>
                <div class="col-4">
                <input 
                    type="text" 
                    id="field-${field.key}-smsVerification" 
                    name="smsVerification" 
                    'required' }
                    class="form-control"
                    placeholder="请输入验证码"
                ></div>
                <div class="col-2">
                    <button type="button" class=" btn btn-secondary" onclick="sendSmsVerification()">获取验证码</button>
                </div>
                </div>
                `;
              }else{
                fieldHtml += `
                <div class="col-sm-10">
                <input 
                    type="text" 
                    id="field-${field.key}" 
                    name="${field.key}" 
                    ${field.defValue ? `value="${field.defValue}"` : ''}
                    ${field.required ? 'required' : ''}
                    class="form-control"
                    data-rule-pattern="^1\d{10}$" data-msg-pattern="请填写有效的手机号码" 
                    placeholder="请输入${field.name}"
                >
                </div>
                `;
              }
              break;
          case 'textarea':
              fieldHtml += `
                 <div class="col-sm-10">
                  <textarea 
                      id="field-${field.key}" 
                      name="${field.key}" 
                      ${field.required ? 'required' : ''}
                      rows="${field.rows ? field.rows: 4}"
                      class="form-control"
                      placeholder="请输入${field.name}"
                  >${field.defValue ? field.defValue : ''}</textarea>
                </div>
              `;
              break;
              
          case 'number':
              fieldHtml += `
                <div class="col-sm-10">
                  <input 
                      type="number" 
                      id="field-${field.key}" 
                      name="${field.key}" 
                      ${field.defValue ? `value="${field.defValue}"` : ''}
                      ${field.required ? 'required' : ''}
                      class="form-control"
                      placeholder="请输入${field.name}"
                  >
                  </div>
              `;
              break;
              
          case 'date':
              fieldHtml += `
                <div class="col-sm-10">
                  <input 
                      type="date" 
                      id="field-${field.key}" 
                      name="${field.key}" 
                      ${field.defValue ? `value="${field.defValue}"` : ''}
                      ${field.required ? 'required' : ''}
                      class="form-control"
                  >
                 </div>
              `;
              break;
              
          case 'multipleSelect':
              fieldHtml += `
                 <div class="col-sm-10">
                  <select  multiple
                      id="field-${field.key}" 
                      name="${field.key}" 
                      ${field.required ? 'required' : ''}
                      class="form-control"
                  >
                      <option value="">请选择${field.name}</option>
                      ${field.options.map(option => `
                          <option value="${option.value}" ${field.defValue === option.value ? 'selected' : ''}>
                              ${option.label}
                          </option>
                      `).join('')}
                  </select>
                  </div>
              `;
              break;
          case 'select':
              fieldHtml += `
                 <div class="col-sm-10">
                  <select 
                      id="field-${field.key}" 
                      name="${field.key}" 
                      ${field.required ? 'required' : ''}
                      class="form-control"
                  >
                      <option value="">请选择${field.name}</option>
                      ${field.options.map(option => `
                          <option value="${option.value}" ${field.defValue === option.value ? 'selected' : ''}>
                              ${option.label}
                          </option>
                      `).join('')}
                  </select>
                  </div>
              `;
              break;  
          case 'radio':
              fieldHtml += `
                  <div class="space-y-2">
                      ${field.options.map((option, index) => `
                          <div class="flex items-center">
                              <input 
                                  type="radio" 
                                  id="field-${field.key}-${index}" 
                                  name="${field.key}" 
                                  value="${option.value}" 
                                  ${field.defValue === option.value ? 'checked' : ''}
                                  ${field.required ? 'required' : ''}
                                  class="h-4 w-4 text-primary focus:ring-primary border-light-3 rounded"
                              >
                              <label for="field-${field.key}-${index}" class="ml-2 block text-sm text-dark">
                                  ${option.label}
                              </label>
                          </div>
                      `).join('')}
                  </div>
              `;
              break;
              
          case 'checkbox':
              fieldHtml += `
                  <div class="space-y-2">
                      ${field.options.map((option, index) => `
                          <div class="flex items-center">
                              <input 
                                  type="checkbox" 
                                  id="field-${field.key}-${index}" 
                                  name="${field.key}" 
                                  value="${option.value}" 
                                  ${field.defValue && field.defValue.includes(option.value) ? 'checked' : ''}
                                  class="h-4 w-4 text-primary focus:ring-primary border-light-3 rounded"
                              >
                              <label for="field-${field.key}-${index}" class="ml-2 block text-sm text-dark">
                                  ${option.label}
                              </label>
                          </div>
                      `).join('')}
                  </div>
              `;
              break;
              
          case 'switch':
              fieldHtml += `
                  <div class="flex items-center">
                      <div class="relative inline-block w-10 align-middle select-none transition duration-200 ease-in">
                          <input 
                              type="checkbox" 
                              id="field-${field.key}" 
                              name="${field.key}" 
                              class="toggle-checkbox absolute block w-6 h-6 rounded-full bg-white border-4 appearance-none cursor-pointer"
                              ${field.defValue === '1' || field.defValue === true ? 'checked' : ''}
                              ${field.required ? 'required' : ''}
                          >
                          <label for="field-${field.key}" class="toggle-label block overflow-hidden h-10 rounded-full bg-light-2 cursor-pointer"></label>
                      </div>
                  </div>
              `;
              break;
      }
      
      // 添加错误提示容器
      //fieldHtml += `<p class="mt-1 text-danger text-xs hidden error-message"></p>`;
      
      fieldWrapper.innerHTML = fieldHtml;
      return fieldWrapper;
  }

  // 处理表单提交
  function handleFormSubmit(event) {
      //event.preventDefault();
      // 收集表单数据
      const formData = new FormData(elements.renderedForm);
      const errors = [];
            
      // 1. 检查必填字段
      const requiredFields = [];

      const captchaVerificationHidden = document.getElementById('captchaVerification');
      const captchaVerification = captchaVerificationHidden.value;
      const smsVerificationEle = document.getElementById('field-creatorPhone-smsVerification');
      
      let smsVerificationVal = ""
      if(smsVerificationEle){
        smsVerificationVal = smsVerificationEle.value;
      }
      const formValues = {
        "customs":{},
        "captchaVerification":captchaVerification,
        "accessUv":Cms.getUniqueVisitor(),
        "smsVerification":smsVerificationVal
      };
      
      // 处理不同类型的字段值
      state.fields.forEach(field => {
          if(field.required){
            requiredFields.push({"key":field.key,"name":field.name,"custom":field.custom})
          }
          //系统默认字段
          if(["title","contactUser","nickname","letterText","letterType","openDesire","creatorPhone","creatorEmail","creatorAddress"].includes(field.key)){
            if (field.type === 'checkbox') {
                  // 复选框可能有多个值
                  formValues[field.key] = [];
                  formData.forEach((value, key) => {
                      if (key === field.key) {
                          formValues[field.key].push(value);
                      }
                  });
              } else if (field.type === 'switch') {
                  // 开关字段转换为布尔值
                  formValues[field.key] = formData.has(field.key);
              } else {
                  // 其他类型字段
                  formValues[field.key] = formData.get(field.key) || '';
              }
          }else{
            formValues["customs"][field.key] = [];
            if (['checkbox','radio','switch','multipleSelect','select'].includes(field.type)){
                formValues["customs"][`${field.key}_cus`] = [];
            }
            //自定义字段
            if (field.type === 'checkbox'||field.type === 'radio') {
                // 复选框可能有多个值
                formData.forEach((value, key) => {
                    if (key === field.key) {
                        formValues["customs"][`${field.key}_cus`].push(value);
                    }
                });
                const selectLabel = getCheckboxLabel(formData,`${field.key}`)
                formValues["customs"][`${field.key}`].push(...selectLabel);
            } else if (field.type === 'switch') {
                // 开关字段转换为布尔值
                formValues["customs"][field.key] = formData.has(field.key);
                formValues["customs"][`${field.key}_cus`] = formData.has(field.key)
                const selectLabel = getCheckboxLabel(formData,`${field.key}`)
                formValues["customs"][`${field.key}`].push(...selectLabel);
            } else if (field.type === 'multipleSelect'||field.type === 'select') {
                // 多选下拉字段
                //formValues["customs"][field.key] = formData.getAll(`${field.key}[]`) || '';
                const selectVal = formData.getAll(`${field.key}`) || ''
                formValues["customs"][`${field.key}_cus`] = selectVal;
                if(Array.isArray(selectVal) ){
                    for (const val of selectVal) {
                        formValues["customs"][`${field.key}`].push(getSelectOptionLabel(`${field.key}`,val));
                    }
                }else{
                    formValues["customs"][`${field.key}`].push(getSelectOptionLabel(`${field.key}`,selectVal));
                }
            } else {
                // 其他类型字段
                formValues["customs"][field.key] = formData.get(field.key) || '';
            }
        }
      });
      
      const action = elements.renderedForm.action;
      const token = sessionStorage.getItem("accessToken")?sessionStorage.getItem("accessToken"):'';
      
      requiredFields.forEach(field => {
        if(field.custom){
            const value = formValues["customs"][`${field.key}`]
            if (!value || value&&value === '') {
                errors.push(`${field.name}为必填项`);
            }
        }else{
            const value = formData.get(field.key);
            if (!value || value.trim() === '') {
                errors.push(`${field.name}为必填项`);
            }
        }
      });
      if(errors&&errors.length > 0){
        showError(`${errors.map(err => `${err}`).join(' ')}`)
        return
      }
      axios.post(action,formValues ,{headers: {"Tenant-Id": Cms.getTenantId(), Authorization: "Bearer " + token,},})
      .then(function (response) {
        if (response.data.code == 0) {
            showError(`写信成功，信件办理情况查询编号是:${response.data.data.letterNo} 查询密码:${response.data.data.queryPass}`);
        }else{
            showError(`${response.data.msg}`)
        }
        //location.href = "/front/letter/post";
      });
      
      // 在实际应用中，这里会发送数据到服务器
      console.log('表单提交数据:', formValues);
}

function trimSpacesAndNewlines(str) {
    if(!str || str === ''){
        return str
    }
    return str.trim();
}
//获取checkbox radio 的lable
function getCheckboxLabel(formData,fieldName) {
    const selectedValues = formData.getAll(`${fieldName}`);
    const selectedLabels = selectedValues.map(value => {
        // 找到value匹配的复选框
        const checkbox = elements.renderedForm.querySelector(`input[name="${fieldName}"][value="${value}"]`);
        if (checkbox) {
            // 通过checkbox的id找到对应的label（for属性与id匹配）
            const label = elements.renderedForm.querySelector(`label[for="${checkbox.id}"]`);
            return label ? trimSpacesAndNewlines(label.textContent) : trimSpacesAndNewlines(value);
        }
        return trimSpacesAndNewlines(value);
    });
    return selectedLabels;
}
//获取select的label
function getSelectOptionLabel(fieldName, value) {
    // 找到对应的select元素
    const selectElement = elements.renderedForm.querySelector(`select[name="${fieldName}"]`);
    // 找到value匹配的option元素
    const optionElement = selectElement.querySelector(`option[value="${value}"]`);
    // 返回option的文本内容
    return optionElement ? trimSpacesAndNewlines(optionElement.textContent) : trimSpacesAndNewlines(value);
}
// 更新表单预览
function updateFormPreview() {
    // 复制表单内容到预览区域
    const formClone = elements.renderedForm.cloneNode(true);
    
    // 移除表单提交事件，避免在预览中提交
    formClone.removeAttribute('id');
    formClone.querySelectorAll('button[type="submit"]').forEach(btn => {
        btn.setAttribute('type', 'button');
        btn.classList.add('opacity-50', 'cursor-not-allowed');
        btn.innerHTML = '<i class="fa fa-lock mr-1"></i> 预览模式';
    });
}
  // 显示错误模态框
function showErrorModal(title, message, details) {
    elements.errorMessage.textContent = message;
    elements.errorDetails.textContent = details;
    elements.errorModal.classList.remove('hidden');
}

// 初始化应用
function initApp() {
    initEventListeners();
}
function getLetterForm(api,letterConfig) {
   axios.get(api+"/model/letter")
      .then(function (response) {
    if (response.data.code === 0) {
       if(response.data.data){
         $("#fields-config").val(response.data.data.itemFields)
         renderForm(letterConfig)
       }
    }
    return response.data.data
  });
}
function sendSmsVerification(){
    const phoneNumber = $("#field-creatorPhone").val()
    if (!Cms.isValidPhoneNumber(phoneNumber)) {
        $("#field-creatorPhone").focus()
        return
    }
    //短信场景模式后端固定
    sendMobileMessage($('#field-creatorPhone'), 6);
}